package com.ruoyi.web.controller.erpbase;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 微信授权Controller
 * 
 * @author ruoyi
 */
@Api(tags = "微信授权接口")
@RestController
@RequestMapping("/wechat")
public class WechatController extends BaseController
{
    @Value("${wechat.appid:}")
    private String appId;

    @Value("${wechat.secret:}")
    private String appSecret;

    /**
     * 通过code获取微信用户openid和session_key
     * 
     * @param code 微信授权code
     * @return 微信用户信息
     */
    @Anonymous
    @ApiOperation("通过code获取微信用户信息")
    @ApiImplicitParam(name = "code", value = "微信授权code", required = true, dataType = "String")
    @GetMapping("/get-ids-by-code")
    public AjaxResult getIdsByCode(@RequestParam("code") String code)
    {
        try
        {
            // 构建微信API URL
            String url = String.format(
                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                appId, appSecret, code
            );

            // 调用微信API
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.getForObject(url, String.class);
            
            // 解析返回结果
            JSONObject jsonObject = JSONObject.parseObject(response);
            
            // 检查是否有错误
            if (jsonObject.containsKey("errcode"))
            {
                Integer errcode = jsonObject.getInteger("errcode");
                String errmsg = jsonObject.getString("errmsg");
                return AjaxResult.error("微信授权失败: " + errmsg + " (错误码:" + errcode + ")");
            }
            
            // 返回成功数据
            return AjaxResult.success(jsonObject);
        }
        catch (Exception e)
        {
            logger.error("获取微信用户信息失败", e);
            return AjaxResult.error("获取微信用户信息失败: " + e.getMessage());
        }
    }
}
